#include "account_qrcode.h"

Account_Qrcode::Account_Qrcode(Http_Get* parent) :
    Http_Get(parent)
{
    get();
}

Account_Qrcode::~Account_Qrcode()
{

}

void Account_Qrcode::get()
{
    QString url = LOGIN_SERVER_HOST + "/jslogin?appid=wx782c26e4c19acffb"
                    "&redirect_uri=" + WX_SERVER_HOST + WX_CGI_PATH + "webwxnewloginpage"
                    "&fun=new&lang=zh_CN&_=" + QString::number(time(NULL));

#if QWX_DEBUG
    qDebug() << "DEBUG:" << __PRETTY_FUNCTION__ << url;
#endif

    Http_Get::get(url);
}

void Account_Qrcode::finished(QNetworkReply* reply)
{
    QString replyStr(reply->readAll());
    QString uuidStr = "";
    QString qruuidStr = "window.QRLogin.uuid = \"";
    int index = -1;

#if QWX_DEBUG
    qDebug() << "DEBUG:" << __PRETTY_FUNCTION__;
    qDebug() << "context:" << replyStr;
#endif

    // TODO: window.QRLogin.code = 200; window.QRLogin.uuid = "395bb96e535e47";
    index = replyStr.indexOf(qruuidStr);
    if (index == -1) {
        qWarning() << "ERROR:" << __PRETTY_FUNCTION__ << "uuid not found!";
        Q_EMIT error();
        return;
    }
    index = index + qruuidStr.size();

    uuidStr = replyStr.mid(index, replyStr.size() - index - QString("\";").size());
#if QWX_DEBUG
    qDebug() << "UUID:" << uuidStr;
#endif
    if (uuidStr == "") {
        Q_EMIT error();
        return;
    }
    Q_EMIT qrcode_changed(uuidStr);
}
